package delivery.order.service.api;

import com.alibaba.fastjson2.JSON;
import delivery.order.service.constant.PathConstant;
import delivery.order.service.pojo.OrderBean;
import delivery.order.service.utils.FolderUtil;
import delivery.order.service.utils.NumberFormatUtils;
import delivery.order.service.utils.UUIDUtils;
import delivery.order.service.utils.response.ResponseUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.poi.ss.usermodel.*;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.LocalConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@CrossOrigin(origins = "*") // 允许所有源
@RestController
@RequestMapping(value = "/main", produces = {"application/json;charset=UTF-8"})
public class MAIN_000_000_000 {

    private static final Logger logger = LoggerFactory.getLogger(MAIN_000_000_000.class);

    @Qualifier("OfficeManager")
    private final OfficeManager officeManager;

    public MAIN_000_000_000(OfficeManager officeManager) {
        this.officeManager = officeManager;
    }

    //生成订单
    @PostMapping(value = "/000_000_000")
    public String doPost(HttpServletRequest request) {

        try (InputStream inputStream = getClass().getResourceAsStream(PathConstant.templatePath)) {
            // 获取请求参数,解析json
            String requestBody = request.getReader().readLine();
            logger.info("requestBody===》{}", requestBody);
            OrderBean orderBean = JSON.parseObject(requestBody, OrderBean.class);
            // 参数校验
            String customerAddress = orderBean.customerAddress;
            if (customerAddress == null || customerAddress.isEmpty()) {
                return ResponseUtils.generateFail("客户地址为空");
            }

            String deliveryTime = orderBean.deliveryTime;
            if (deliveryTime == null || deliveryTime.isEmpty()) {
                return ResponseUtils.generateFail("送货日期为空");
            }

            List<OrderBean.ProductBean> productList = orderBean.productList;
            if (productList == null || productList.isEmpty()) {
                return ResponseUtils.generateFail("货物列表为空");
            }

            String handlerPerson = orderBean.handlerPerson;
            if (handlerPerson == null || handlerPerson.isEmpty()) {
                handlerPerson = "   ";
            }

            // 读取resources目录下的Excel模板
            if (inputStream == null) {
                return ResponseUtils.generateFail("模板异常");
            }
            // 创建工作簿对象
            try (Workbook workbook = WorkbookFactory.create(inputStream)) {
                Sheet sheet = workbook.getSheetAt(0);
                // 获取单元格样式（用于后面克隆）
                Row headerRow = sheet.getRow(4);
                CellStyle referenceStyle = headerRow.getCell(0).getCellStyle();

                // 填充单号
                Row row1 = sheet.getRow(1);
                Cell cell1 = row1.createCell(0);
                fillOrderNumber(workbook, cell1);

                // 填充客户地址
                Row row2 = sheet.getRow(2);
                Cell cell2 = row2.createCell(1);
                fillCustomerAddress(workbook, cell2, referenceStyle, customerAddress);

                // 填充送货时间
                Cell cell5 = row2.createCell(4);
                fillDeliveryTime(workbook, cell5, referenceStyle, deliveryTime);

                // 填充货物列表，从第5行开始，也就是索引4开始填充
                List<String> allTotalList = new ArrayList<>();
                int goodsStartLines = 4;//开始填充的行数
                int size = productList.size();
                for (int i = goodsStartLines; i < goodsStartLines + size; i++) {
                    Row row = sheet.getRow(i);//获取行数
                    OrderBean.ProductBean productBean = productList.get(i - goodsStartLines);
                    String productName = productBean.productName;
                    String productUnit = productBean.productUnit;
                    String productQuantity = productBean.productQuantity;
                    String productPrice = productBean.productPrice;
                    String productRemarks = productBean.productRemarks;
                    String total;
                    // 货物名
                    if (productName == null || productName.isEmpty()) {
                        return ResponseUtils.generateFail("货物名称为空");
                    }
                    // 单位
                    if (productUnit == null || productUnit.isEmpty()) {
                        return ResponseUtils.generateFail("货物单位为空");
                    }
                    // 数量
                    HashMap<String, String> quantityMap = NumberFormatUtils.toTwoDecimals(productQuantity);
                    if (!"000".equals(quantityMap.get("code"))) {
                        return ResponseUtils.generateFail(quantityMap.get("str"));
                    } else {
                        productQuantity = quantityMap.get("str");
                    }
                    // 单价
                    HashMap<String, String> priceMap = NumberFormatUtils.toTwoDecimals(productPrice);
                    if (!"000".equals(priceMap.get("code"))) {
                        return ResponseUtils.generateFail(priceMap.get("str"));
                    } else {
                        productPrice = priceMap.get("str");
                    }
                    // 总计
                    total = NumberFormatUtils.multiplyDecimalFormat(productQuantity, productPrice);
                    allTotalList.add(total);
                    if (productRemarks == null || productRemarks.isEmpty()) {
                        productRemarks = "";
                    }
                    // 填充
                    fillProductCell(workbook, referenceStyle, row, 0, productName);
                    fillProductCell(workbook, referenceStyle, row, 1, productUnit);
                    fillProductCell(workbook, referenceStyle, row, 2, productQuantity);
                    fillProductCell(workbook, referenceStyle, row, 3, productPrice);
                    fillProductCell(workbook, referenceStyle, row, 4, total);
                    fillProductCell(workbook, referenceStyle, row, 5, productRemarks);
                }

                // 填充总计行,索引13开始填充
                int totalRows = 13;
                Row row9 = sheet.getRow(totalRows);
                Cell cell9 = row9.createCell(1);
                String allTotal = NumberFormatUtils.calculateSum(allTotalList);
                fillTotal(workbook, cell9, referenceStyle, allTotal);

                // 填充制单人信息
                Row row13 = sheet.getRow(16);
                Cell cell13 = row13.createCell(4);
                fillRemarks(workbook, cell13, handlerPerson);

                //格式调整-货物数量最大行数
                int maxGoodsRows = 9;
                if (size > maxGoodsRows) {
                    return ResponseUtils.generateFail("货物数量超过模板最大行数");
                }
                // 模板货物行数最大是10，行数不满，就需要删除留空的行
                if (size < maxGoodsRows) {
                    // 调整格式，把留空的行数删除
                    int LastRowIndex = 12;//货物行最后一行的索引
                    // 计算需要保留的总行数：表头行数(索引从0开始) + 实际数据行数
                    int rowsToKeep = 3 + size;
                    // 从最后一行开始删除
                    for (int i = LastRowIndex; i > rowsToKeep; i--) {
                        Row removingRow = sheet.getRow(i);
                        sheet.removeRow(removingRow);
                    }
                    //把删除后留空的行往上提升
                    int firstRowToShift = 13; // 第14行开始（总计那一行）
                    int lastRowToShift = 16; // 到最后一行（联系方式那一行）
                    // 参数1：开始行数，参数2：结束行数，参数3：移动几行，负号表示上移
                    sheet.shiftRows(firstRowToShift, lastRowToShift, -(maxGoodsRows - size));//6-3：货物行总共6行（固定），减去实际行，得到需要移动几行
                }

                // 设置纸张大小，注意：一个 Sheet 可能已经有一个默认的 PrintSetup，我们直接获取它来修改
                PrintSetup printSetup = sheet.getPrintSetup();
                // 核心步骤：设置纸张大小为 A5
                printSetup.setPaperSize(PrintSetup.A5_PAPERSIZE);
                // 设置为横向
                printSetup.setLandscape(true); // true 为横向，false（默认）为纵向
                // 设置为适应一页宽和一页高
                sheet.setFitToPage(true);
                printSetup.setFitWidth((short) 1);
                printSetup.setFitHeight((short) 1);

                // 检查文件夹
                FolderUtil.checkAndCreateOutputFolder();

                // 保存文件到D盘
                String xlsxName = UUIDUtils.generate() + ".xlsx";
                String outputFilePath = PathConstant.getOutputFolderPath() + "/" + xlsxName;
                try (FileOutputStream outputStream = new FileOutputStream(outputFilePath)) {
                    workbook.write(outputStream);
                }

                // 转成pdf
                String pdfName = UUIDUtils.generate() + ".pdf";
                String outputPDFPath = PathConstant.getOutputFolderPath() + "/" + pdfName;  // 输出目录
                // 执行转换
                LocalConverter.builder().officeManager(officeManager)//
                        .build()//
                        .convert(new File(outputFilePath))//源文件目录
                        .to(new File(outputPDFPath))//目标文件目录
                        .execute();

                // 转换完成删除表格
                FolderUtil.deleteFile(outputFilePath);

                logger.warn("完成输出：{}", outputPDFPath);

                //返回数据
                HashMap<String, String> dataMap = new HashMap<>();
                dataMap.put("pdfName", pdfName);
                return ResponseUtils.generateSucceed(dataMap);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 填充客户地址
     *
     * @param workbook       工作簿
     * @param cell           被填充的单元格
     * @param referenceStyle 单元格样式
     */
    private void fillCustomerAddress(Workbook workbook, Cell cell, CellStyle referenceStyle, String customerAddress) {
        cell.setCellValue(customerAddress);
        CellStyle newStyle = workbook.createCellStyle();
        newStyle.cloneStyleFrom(referenceStyle);
        cell.setCellStyle(newStyle);
    }

    // 填充订单号
    private void fillOrderNumber(Workbook workbook, Cell cell) {
        long l = System.currentTimeMillis();
        cell.setCellValue("No." + l);
        cell.setCellStyle(setRightCenterStyle(workbook));
    }

    //填充送货时间
    private void fillDeliveryTime(Workbook workbook, Cell cell, CellStyle referenceStyle, String deliveryTime) {
        cell.setCellValue("送货时间：" + deliveryTime);
        CellStyle newStyle = workbook.createCellStyle();
        newStyle.cloneStyleFrom(referenceStyle);
        cell.setCellStyle(newStyle);
    }

    //填充货物
    private void fillProductCell(Workbook workbook, CellStyle referenceStyle, Row row, int column, String value) {
        Cell cell = row.createCell(column);//指定列的单元格
        cell.setCellValue(value);//填充数据
        CellStyle newStyle = workbook.createCellStyle();
        newStyle.cloneStyleFrom(referenceStyle);
        cell.setCellStyle(newStyle);
    }

    //填充总计
    private void fillTotal(Workbook workbook, Cell cell, CellStyle referenceStyle, String total) {
        cell.setCellValue(total);
        CellStyle newStyle = workbook.createCellStyle();
        newStyle.cloneStyleFrom(referenceStyle);
        cell.setCellStyle(newStyle);
    }

    //填充最后一行
    private void fillRemarks(Workbook workbook, Cell cell, String handlerPerson) {
        String remarks = "制单人（盖章）：" + handlerPerson;
        cell.setCellValue(remarks);
        cell.setCellStyle(setRightCenterStyle(workbook));
    }

    //右边居中样式
    private CellStyle setRightCenterStyle(Workbook workbook) {
        // 创建单元格样式
        CellStyle rightCenterStyle = workbook.createCellStyle();
        // 设置水平对齐为右对齐
        rightCenterStyle.setAlignment(HorizontalAlignment.RIGHT);
        // 设置垂直对齐为居中
        rightCenterStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = workbook.createFont();
        font.setFontName("微软雅黑");      // 设置字体为宋体
        font.setFontHeightInPoints((short) 12.5);  // 设置字号为12磅
        rightCenterStyle.setFont(font);
        return rightCenterStyle;
    }


}
